import React, { Fragment } from "react";
import { FormInstance } from "antd/lib/form";
import {
  Form,
  Input,
  message,
  Row,
  Col,
  Button,
  List,
  Avatar,
  Spin,
} from "antd";
import { connect } from "react-redux";
import { withRouter } from "react-router-dom";

import style from "./chat.module.scss";
import { MqttContext } from "../../util/mqttContext";
const { TextArea } = Input;
class Chat extends React.Component {
  formRef = React.createRef();
  static contextType = MqttContext; //指定context

  constructor(props) {
    super(props);
    this.state = {
      regFlag: false, //是否注册成功
      spinLoading: false,
      rcvmsg: [
        {
          username: "张三",
          msgdata: "天王盖地虎",
        },
      ],
      toid: "",
      sendmsg: [],
      subtopic: "",
      pubtopic: "",
    };
  }
  state = {
    confirmDirty: false,
  };
  subChatTopic = (toid) => {
    //开始订阅指定主题,先检查是否链接成功，再进行订阅
    let _this = this;
    let sub = new Promise((reslove, reject) => {
      function waitSub() {
        console.log("进入sub，检测是否链接成功");
        if (_this.props.mqtt.connected) {
          console.log("链接成功，开始准备订阅");
          let subtopic = `m2m/from/${toid}/to/${_this.context.clientId}/chat/`;
          let pubtopic = `m2m/from/${_this.context.clientId}/to/${toid}/chat/`;
          _this.setState({
            subtopic: subtopic,
            pubtopic: pubtopic,
          });
          console.log("开始订阅聊天主题", subtopic);
          console.log("发布主题是", pubtopic);
          _this.context.subscribe(subtopic, 1);
          console.log("订阅完成");
          reslove();
        } else {
          console.log("未链接成功，一秒后再试");
          setTimeout(() => {
            waitSub();
          }, 1000);
        }
      }
      waitSub();
    });
    return sub;
  };

  componentDidMount() {
    //临时设置自己的id，正式环境是登陆后获取
    this.formRef.current.setFieldsValue({
      fromid: this.context.clientId,
    });
  }

  handleSubmit = async () => {
    try {
      const values = await this.formRef.current.validateFields();

      let data = {
        username: this.context.clientId,
        data: values.msg,
      };
      //发送数据
      /* eslint-disable no-undef */
      let message = new Paho.MQTT.Message(values.msg);
      message.destinationName = this.state.pubtopic;
      this.context.send(message);
      //更新发送信息
      this.setState({
        sendmsg: [...this.state.sendmsg, data],
      });
    } catch (errorInfo) {
      message.error("请填写对方id");
    }
  };
  regsiter = async () => {
    // console.log("this.formRef", this.formRef);
    try {
      const values = await this.formRef.current.validateFields();
      let toid = values.toid;
      let fromid = values.toid;
      this.setState({
        spinLoading: true,
        toid,
        toid,
      });
      // //开始订阅指定主题
      this.subChatTopic(toid).then(() => {
        this.setState({
          spinLoading: false,
        });
        this.setState({
          regFlag: true,
        });
      });
    } catch (errorInfo) {
      // message.error("请填写对方id");
      // console.log("Failed:", errorInfo);
    }
  };
  render() {
    const { spinLoading } = this.state;
    const formItemLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        span: 9,
      },
    };

    return (
      <div className="chat">
        {spinLoading ? (
          <div className="spinLoading">
            <Spin tip="连接中，请稍等..."></Spin>{" "}
          </div>
        ) : null}
        <div>{this.props.mqtt.data}</div>
        <div className={style.his}>
          {/* <div>
            {console.log("this.props.mqtt", this.props.mqtt)}
            {`MQTT 收到topic 为 ${this.props.mqtt.newMsg.topic} 的消息，具体内容为: ${this.props.mqtt.newMsg.payload}, 消息服务等级为 ${this.props.mqtt.newMsg.qos}`}
          </div> */}{" "}
          {this.state.regFlag ? (
            <Row>
              <Col span={12} className={style.rcvMsg}>
                <List
                  itemLayout="horizontal"
                  dataSource={this.props.mqtt.chatData}
                  renderItem={(item) => (
                    <List.Item>
                      <List.Item.Meta
                        avatar={
                          <Avatar
                            style={{
                              color: "#f56a00",
                              backgroundColor: "#fde3cf",
                            }}
                          >
                            {this.state.toid.slice(0, 1)}
                          </Avatar>
                        }
                        title={item.username}
                        description={item.msgdata}
                      />
                    </List.Item>
                  )}
                />
              </Col>

              <Col span={12} className={style.sendMsg}>
                <List
                  itemLayout="horizontal"
                  dataSource={this.state.sendmsg}
                  renderItem={(item) => (
                    <List.Item>
                      <List.Item.Meta
                        avatar={
                          <Avatar
                            style={{
                              color: "#f56a00",
                              backgroundColor: "#fde3cf",
                            }}
                          >
                            {this.context.clientId.slice(0, 1)}
                          </Avatar>
                        }
                        title={item.username}
                        description={item.data}
                      />
                    </List.Item>
                  )}
                />
              </Col>
            </Row>
          ) : null}
        </div>
        <Form {...formItemLayout} ref={this.formRef}>
          {this.state.regFlag == false ? (
            <Fragment>
              <Row>
                <Col span={8}>
                  {" "}
                  <Form.Item
                    name="toid"
                    label="对方id"
                    rules={[{ required: true }]}
                  >
                    <Input />
                  </Form.Item>{" "}
                </Col>
                <Col span={8}>
                  {" "}
                  <Form.Item
                    name="fromid"
                    label="自己id"
                    rules={[{ required: true }]}
                  >
                    <Input />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  {" "}
                  <Form.Item {...tailFormItemLayout}>
                    <Button type="primary" onClick={this.regsiter}>
                      注册
                    </Button>
                  </Form.Item>{" "}
                </Col>
              </Row>
            </Fragment>
          ) : null}

          {this.state.regFlag == true ? (
            <Fragment>
              <Row>
                <Col span={20}>
                  {" "}
                  <Form.Item
                    name="msg"
                    rules={[{ required: true, message: "请输入消息" }]}
                  >
                    <TextArea rows={4} />
                  </Form.Item>
                </Col>
                <Col span={4}>
                  {" "}
                  <Form.Item {...tailFormItemLayout}>
                    <Button type="primary" onClick={this.handleSubmit}>
                      发送
                    </Button>
                  </Form.Item>
                </Col>
              </Row>
            </Fragment>
          ) : null}
        </Form>
      </div>
    );
  }
}
// export default ;

const mapStateToProps = (state) => state;
const mapDispatchToProps = (dispatch) => ({});
export default connect(mapStateToProps, mapDispatchToProps)(withRouter(Chat));
